import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// 接收环境变量
const baseURL = process.env.VUE_APP_BASE_API
// create an axios instance
// 自定义axios，配置跟路径
const service = axios.create({
  baseURL: baseURL // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
})

// request interceptor
// 请求兰拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// 响应拦截器
// response interceptor
service.interceptors.response.use(
  response => {
    const { message, data, success } = response.data
    if (success) {
      return data
    } else {
      Message.error(message)
      return Promise.reject(new Error(message))
    }

    // if the custom code is not 20000, it is judged as an error.
  },
  error => {
    // 如果401了
    if (error.response.status === 401) {
      if (router.currentRoute.path === '/login') return
      console.dir(error)
      store.dispatch('user/delAction')
      Message.error('身份过期')
      router.replace(`/login?Path=${router.currentRoute.path}`)
      // console.log(router.currentRoute.path)
    }
    return Promise.reject(error)
  }
)

export default service
